<template>
  <!-- 导航 -->
  <el-row style="margin: 10px;background-color: ghostwhite;padding: 15px">
    <el-col :span="24">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item>首页</el-breadcrumb-item>
        <el-breadcrumb-item>项目管理</el-breadcrumb-item>
        <el-breadcrumb-item>所有项目列表</el-breadcrumb-item>
      </el-breadcrumb>
    </el-col>
  </el-row>
  <!-- 搜索栏-->
  <el-row style="margin: 10px;background-color: ghostwhite;padding: 15px">
    <el-col :span="24">
      <el-form :model="projectQuery" inline>
        <el-form-item label="项目名称">
          <el-input v-model="projectQuery.projectName"/>
        </el-form-item>
        <el-form-item label="项目状态">
          <el-select style="width: 100px" v-model="projectQuery.projectStatus">
            <el-option :value="0" label="全部"/>
            <el-option :value="1" label="草稿"/>
            <el-option :value="2" label="发布"/>
            <el-option :value="3" label="暂停"/>
            <el-option :value="4" label="意外"/>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
              v-model="startTimes"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
              v-model="endTimes"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="loadProjects" type="primary">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
  <el-row style="margin: 0px 10px;background-color: ghostwhite;padding: 0px 10px">
    <el-col :span="24">

      <el-button type="primary" @click="projectAddWinDialogVisible=true">新增</el-button>
      <el-button type="primary" @click="toEdits">编辑</el-button>
      <el-button type="primary" @click="toDeletes">删除</el-button>
      <el-button type="primary" @click="toArchives">归档</el-button>
      <el-button type="primary" @click="toReleases">发布</el-button>

    </el-col>
  </el-row>
  <el-row style="margin: 0px 10px;padding: 0px 15px">
    <el-col :span="24">
      <el-table :data="projects" border stripe ref="projectTable">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="projectId" label="#">
          <template #default="scope">
            <el-link type="success" @click="showProjectDetail(scope.row.projectId)">{{ scope.row.projectId }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="projectName" label="项目名称"/>
        <el-table-column prop="user.username" label="项目负责人"/>
        <el-table-column label="任务数量">
          <template #default>
            100
          </template>
        </el-table-column>
        <el-table-column prop="projectStatus" label="项目状态">
          <template #default="scope">
            <el-tag type="info" v-if="scope.row.projectStatus == 1">草稿</el-tag>
            <el-tag type="primary" v-else-if="scope.row.projectStatus == 2">发布</el-tag>
            <el-tag type="warning" v-else-if="scope.row.projectStatus == 3">暂停</el-tag>
            <el-tag type="danger" v-else-if="scope.row.projectStatus == 4">意外</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间"/>
        <el-table-column prop="endTime" label="结束时间"/>
        <el-table-column prop="createTime" label="创建时间"/>
        <el-table-column label="操作" width="330">
          <template #default="scope">
            <el-button-group>
              <template v-if="scope.row.userId == currUserId">
                <el-button @click="toEdit(scope.row.projectId)" size="small" type="primary">编辑</el-button>
                <el-button @click="toArchive(scope.row)" size="small" type="info">归档</el-button>
                <el-button @click="toDelete(scope.row)" size="small" type="danger">删除</el-button>
              </template>
              <el-button size="small" type="primary">任务</el-button>
              <el-button size="small" type="primary">日历</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>
  <el-row style="margin: 0px 10px;padding: 0px 15px">
    <el-col :span="24">
      <el-pagination @change="changePage" background layout="prev, pager, next" :total="total"/>
    </el-col>
  </el-row>
  <!-- 新增项目的弹窗 -->
  <el-dialog v-model="projectAddWinDialogVisible"
             title="新增项目"
             width="50%"
  >
    <template #default>
      <el-form :model="newProject">
        <el-form-item label="项目id">
          <el-input v-model="newProject.projectId"/>
        </el-form-item>
        <el-form-item label="项目名称">
          <el-input v-model="newProject.projectName"/>
        </el-form-item>
        <el-form-item label="项目描述">
          <el-input type="textarea" v-model="newProject.projectDesc"/>
          <!--           富文本编辑器的结构 -->
          <!--          <div style="border: 1px solid #ccc">-->
          <!--            <Toolbar-->
          <!--                style="border-bottom: 1px solid #ccc"-->
          <!--                :editor="editorRef"-->
          <!--                :defaultConfig="toolbarConfig"-->
          <!--                :mode="mode"-->
          <!--            />-->
          <!--            <Editor-->
          <!--                style="height: 500px; overflow-y: hidden;"-->
          <!--                v-model="valueHtml"-->
          <!--                :defaultConfig="editorConfig"-->
          <!--                :mode="mode"-->
          <!--                @onCreated="handleCreated"-->
          <!--            />-->
          <!--          </div>-->
        </el-form-item>
        <el-form-item label="项目负责人">
          <el-input v-model="newProject.userId"/>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
              v-model="newProject.startTimes"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
              v-model="newProject.endTimes"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="projectAddWinDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addProjectSubmit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!--   展示项目详情的弹窗 -->
  <el-dialog v-model="projectShowWinDialogVisible"
             title="项目详情"
             width="50%">
    <!--    <el-table :data="projectDetails">-->
    <el-row>
      <el-col :span="12">
        项目id:{{ projectDetails.projectId }}
      </el-col>
      <el-col :span="12">
        项目名称:{{ projectDetails.projectName }}
      </el-col>
      <el-col :span="12">
        项目描述:{{ projectDetails.projectDesc }}
      </el-col>
      <el-col :span="12">
        项目负责人:{{ projectDetails.username }}
      </el-col>
      <el-col :span="12">
        项目开始时间:{{ projectDetails.startTime }}
      </el-col>
      <el-col :span="12">
        项目结束时间:{{ projectDetails.endTime }}
      </el-col>
    </el-row>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="projectShowWinDialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <ProjectEdit :project-id="editProjectId" @editComplete="loadProjects()"/>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {onBeforeUnmount, ref, shallowRef, onMounted} from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import projectRequest from "@/api/project.js";
import {useRouter} from "vue-router";
import ProjectEdit from "@/views/project/project-edit.vue"
import axios from "axios";
import {ElMessage} from "element-plus";
import {ElMessageBox} from 'element-plus'

// 封装搜索数据的对象
let projectQuery = ref({})
// 封装两个时间范围
let startTimes = ref([]);
let endTimes = ref([]);
// 查询的项目列表
let projects = ref([]);
// 总条数，默认0
let total = ref(0);
// 当前页码，默认1
let curPage = ref(1);
//当前项目详情id默认0
let curProjectId = ref(0);
// 编辑的projectId
let editProjectId = ref(-1);
// 当前登录用户的编号
let currUserId = ref();
let router = useRouter();
// 新增项目的弹窗标记
let projectAddWinDialogVisible = ref(false);
// 展示项目详情的弹窗标记
let projectShowWinDialogVisible = ref(false);
// 保存新增项的表单的数据
let newProject = ref({});
let projectDetails = ref({});
let projectTable = ref(null)
// console.log("projects为"+projects.value)
// 富文本编辑器相关的属性
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML ，如果我们修改了内容，这里会跟着变化
const valueHtml = ref()
// 工具栏配置
const toolbarConfig = {}

const editorConfig = {placeholder: '请输入内容...'}


// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}


/**
 * 新增项目的提交按钮事件
 */
function addProjectSubmit() {

  newProject.value.startTimeBegin = newProject.value.startTimes[0];

  newProject.value.startTimeEnd = newProject.value.startTimes[1];

  newProject.value.endTimeBegin = newProject.value.endTimes[0];

  newProject.value.endTimeEnd = newProject.value.endTimes[1];

  projectRequest.saveNewProject(newProject.value, res => {
    if (res.code == 200) {
      console.log("成功")
    }
    projectAddWinDialogVisible.value = false
  })

}

/**
 * 加载项目列表
 */
function loadProjects() {
  //处理查询条件，处理时间范围
  if (startTimes.value[0]) {
    projectQuery.value.startTimeBegin = startTimes.value[0];
  }
  if (startTimes.value[1]) {
    projectQuery.value.startTimeEnd = startTimes.value[1];
  }
  if (endTimes.value[0]) {
    projectQuery.value.endTimeBegin = endTimes.value[0];
  }
  if (endTimes.value[1]) {
    projectQuery.value.endTimeEnd = startTimes.value[1];
  }
  // projectQuery.value.userId=currUserId.value
  projectQuery.value.userId=2

  // 调用API来查询项目列表
  projectRequest.loadProjects(projectQuery.value, curPage.value, 10, res => {
    // 这里的res就是后端返回的结果
    // 总条数赋值
    total.value = res.data.total;
    // 将查询的列表赋值给projects
    projects.value = res.data.list;
    // console.log("projects的数据为:" + projects.value)

  })
}

// 分页事件
function changePage(value) {
  curPage.value = value;
  loadProjects();
}

onMounted(() => {
  loadProjects();
  // 从localStorage中获取用户编号
  currUserId.value = localStorage.getItem("userId");
  if (currUserId.value == undefined || currUserId.value == '') {
    // 进入登录页面
    router.push("/");
  }
})
projectDetails

//展示项目详情
function showProjectDetail(projectId) {
  // console.log("projectId")
  // console.log(projectId)
  curProjectId = projectId
  // console.log("当前项目详情为 curProjectId")
  // console.log(curProjectId)
  projectShowWinDialogVisible.value = true;
  projectRequest.selectProjectDetailsByProjectId(projectId, res => {
    // console.log("project-list里的projectId为"+projectId)
    projectDetails.value = res.data
    // console.log("project-list里的projectDetails.value为"+ projectDetails.value)
  })

}

/**
 * 工具栏编辑按钮事件
 */
function toEdits() {
  let selectedRows = projectTable.value.getSelectionRows();
  if (selectedRows.length == 0) {
    ElMessage({
      type: "warning",
      message: "你没有选择任何数据"
    })
  } else if (selectedRows.length > 1) {
    ElMessage({
      type: "warning",
      message: "你只能编辑一条数据"
    })
  } else if (selectedRows[0].userId != currUserId.value) {
    ElMessage({
      type: "warning",
      message: "你只能编辑你自己的数据"
    })
  } else toEdit(selectedRows[0].value)
}

/**
 * 工具栏删除按钮事件
 */
function toDeletes() {
  let selectedRows = projectTable.value.getSelectionRows();
  if (selectedRows.length == 0) {
    ElMessage({
      type: "warning",
      message: "你没有选择任何数据"
    })
    return
  }
  ElMessageBox.confirm(
      '您确定要将选中的项目删除吗？',
      '提示',
      {
        confirmButtonText: '是的',
        cancelButtonText: '点错了',
        type: 'warning',
      }
  ).then(() => {
    let noCurUserProjectNames = [];
    let projectIds = [];
    selectedRows.forEach(row => {
      if (row.userId != currUserId.value) {
        noCurUserProjectNames.push(row.projectName)
      }
      projectIds.push(row.projectId)
    })
    if (noCurUserProjectNames.length>0){
      ElMessage({
        type:"warning",
        message:"您选中的项目中，有以下项目[" + noCurUserProjectNames.join(",") + "]并非您管理的，不能删除"
      });
      return;
    }
    projectRequest.deletesProject(projectIds,res=>{
      if(res.code == 200){
        ElMessage({
          type:"success",
          message:"成功删除[" + res.data + "]条数据"
        })
        loadProjects();
      }else{
        ElMessage({
          type:"warning",
          message:"删除失败"
        })
      }
    });
  }).catch(()=>{});

}
/**
 * 工具栏发布按钮事件
 * @param
 */
function toReleases() {
  let selectedRows = projectTable.value.getSelectionRows();
  if (selectedRows.length == 0) {
    ElMessage({
      type: "warning",
      message: "你没有选择任何数据"
    })
    return;
  }
  ElMessageBox.confirm(
      '您确定要将选中的项目发布吗？',
      '提示',
      {
        confirmButtonText: '是的',
        cancelButtonText: '点错了',
        type: 'warning',
      }
  ).then(() => {
    let noCurUserProjectNames = [];
    let projectIds = [];
    selectedRows.forEach(row => {
      if (row.userId != currUserId.value) {
        noCurUserProjectNames.push(row.projectName)
      }
      projectIds.push(row.projectId)
    })
    if (noCurUserProjectNames.length > 0) {
      ElMessage({
        type: "warning",
        message: "您选中的项目中，有以下项目[" + noCurUserProjectNames.join(",") + "]并非您管理的，你没有发布权限"
      })
      return;
    }
    projectRequest.releases(projectIds, res => {
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "成功发布[" + res.data + "]条数据"
        })
        loadProjects();
      } else {
        ElMessage({
          type: "warning",
          message: "发布失败"
        })
      }
    });
  }).catch(() => {
  });

}

function toArchives() {
  let selectedRows = projectTable.value.getSelectionRows();
  if (selectedRows.length == 0) {
    ElMessage({
      type: "warning",
      message: "你没有选择任何数据"
    })
    return;
  }
  ElMessageBox.confirm(
      '您确定要将选中的项目归档吗？',
      '提示',
      {
        confirmButtonText: '是的',
        cancelButtonText: '点错了',
        type: 'warning',
      }
  ).then(() => {

    let noCurUserProjectNames = [];
    let draftProjectName = []
    let projectIds = [];
    selectedRows.forEach(row=>{
      if(row.userId != currUserId.value){
        noCurUserProjectNames.push(row.projectName);
      }
      if(row.projectStatus == 1){
        draftProjectName.push(row.projectName);
      }
      projectIds.push(row.projectId);
    })
    if(noCurUserProjectNames.length > 0){
      ElMessage({
        type:"warning",
        message:"您选中的项目中，有以下项目[" + noCurUserProjectNames.join(",") + "]并非您管理的，你没有归档权限"
      });
      return;
    }
    if(draftProjectName.length > 0){
      ElMessage({
        type:"warning",
        message:"您选中的项目中，有以下项目[" + draftProjectName.join(",") + "]属于草稿状态，不能执行归档操作"
      });
      return;
    }
    // 调用API进行归档操作
    projectRequest.archives(projectIds,res=>{
      if(res.code == 200){
        ElMessage({
          type:"success",
          message:"成功归档[" + res.data + "]条数据"
        })
        loadProjects();
      }else{
        ElMessage({
          type:"warning",
          message:"归档失败"
        })
      }
    });
  }).catch(()=>{});
}
/**
 * 行编辑按钮事件
 * @param projectId
 */
function toEdit(projectId) {
  // 修改响应式变量editProjectId的值
  editProjectId.value = projectId;
}

/**
 * 行删除按钮事件
 * @param projectId
 */
function toDelete(project) {
  ElMessageBox.confirm(
      "你确定要删除" + project.projectName + "删除吗?",
      "warning", {
        confirmButtonText: '是的',
        cancelButtonText: '点错了',
        type: 'warning',
      }
  ).then(() => {
    projectRequest.deleteProject(project.projectId, res => {
      ElMessage({
        type: "success",
        message: "操作完成"
      });
      loadProjects();
    })
  }).catch(() => {
  })
}

/**
 * 行归档按钮事件
 * @param projectId
 */
function toArchive(project) {
  ElMessageBox.confirm(
      '您确定要将项目[' + project.projectName + "]归档吗？",
      'Warning',
      {
        confirmButtonText: '是的',
        cancelButtonText: '点错了',
        type: 'warning',
      }
  ).then(() => {
    projectRequest.archiveProject(project.projectId, res => {
      ElMessage({
        type: "success",
        message: "操作完成"
      });
      loadProjects();
    })
  }).catch(() => {
  });
}

/**
 * 工具栏归档按钮事件
 * @param
 */
function editProject() {

}
</script>

<style scoped>

</style>